import modelExtend from 'dva-model-extend'
import { lwjPageModel } from 'utils/model'
import { query, getName } from './services/financialAccountBalanceRecord'
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';


export default modelExtend(lwjPageModel, {
  namespace: 'financialAccountBalanceRecord',
  state: {
    currentItem: {},
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    distributor: {},
    isExpand: false,
    queryParam: {},
    financialAccountId:{}
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        const match = pathToRegexp('/financialAccountBalanceRecord/:id').exec(pathname);
        if (match) {
          const id = match[1];
          dispatch({
            type: 'query',
            payload: {
              financialAccountId: id
            }
          })
          dispatch({
            type: 'setDistributorName',
            payload: {
              id: id
            }
          })
          dispatch({
            type: 'setFinancialAccountId',
            payload: {
              id: id
            }
          })
        }
      })
    }
  },
  effects: {
    * query({
      payload
    }, { select, call, put }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      });

      const pageOptions = yield select(({ financialAccountBalanceRecord }) => financialAccountBalanceRecord.pageOptions);
      const queryParam = yield select(({ financialAccountBalanceRecord }) => financialAccountBalanceRecord.queryParam);

      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...queryParam
        },
      };
      const data = yield call(query, queryPayload);
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    * setDistributorName({
      payload
    }, { select, call, put }) {
      const data = yield call(getName, payload);
      yield put({
        type: 'setName',
        payload: data
      })
    }
  },
  reducers: {
    setName(state, { payload }) {
      return {
        ...state,
        distributor: payload.result
      }
    },
    setFinancialAccountId(state, { payload }) {
      return {
        ...state,
        financialAccountId: payload.id
      }
    },
     expandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: true
      }
    },
    unExpandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: false
      }
    },
  }
})
